package com.mlyol.prototype;

import java.io.*;

public class Demo2 {

    public static void main(String[] args) throws Exception {
        Sheep sheep = new Sheep("sb", 1);
        sheep.setFriend(new Sheep("sb2", 2));
        Sheep sheep2 = (Sheep) sheep.clone();

        System.out.println(sheep.getFriend().hashCode());
        System.out.println(sheep2.getFriend().hashCode());

    }

    static class Sheep implements Cloneable, Serializable {
        String name;
        int age;
        Sheep friend;

        public Sheep(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public Sheep getFriend() {
            return friend;
        }

        public void setFriend(Sheep friend) {
            this.friend = friend;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        protected Object clone() {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(this);


                ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
                ObjectInputStream ois = new ObjectInputStream(bis);
                return ois.readObject();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public String toString() {
            return "Sheep{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

}
